package com.yihaodian.index.solr;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;

import com.google.common.base.Joiner;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.yihaodian.api.index.IndexDoc;
import com.yihaodian.api.index.IndexRequest;
import com.yihaodian.index.IndexException;
import com.yihaodian.index.meta.Fields;

public class SolrIndexCommandBuilder {
	static Logger logger = Logger.getLogger(SolrIndexCommandBuilder.class);

	Joiner joiner = Joiner.on(",");

	/**
	 * solr update command .
	 * 
	 * 
	 * http://wiki.apache.org/solr/UpdateJSON
	 * 
	 * 
	 * @param request
	 * @return
	 */
	public List<String> buildCommand(IndexRequest request) {
//		logger.info("buildCommand " + request.getIndexName());

		Collection<IndexDoc> docs = request.getDocs();

		List<String> commands = new ArrayList<String>(docs.size());
		String command = null;
		for (IndexDoc indexDoc : docs) {
			String jsonDoc = indexDoc.getJsonDoc();

			String uid = indexDoc.getId();
			boolean isDelete = indexDoc.isDelete();

			if (isDelete) {
				command = toDeleteCommand(uid);
			} else {
				command = toAddCommand(jsonDoc);
			}

			commands.add(command);
		}

		return commands;
	}

	String getUid(JsonObject json) {
		JsonElement _uid = json.get(Fields.id_field);
		if (_uid == null)
			throw new IndexException("must provide " + Fields.id_field);
		String uid = _uid.getAsString();

		return uid;
	}

	boolean isDelete(JsonObject json) {
		JsonElement delete = json.get(Fields.delete_field);
		// JsonPrimitive

		boolean isDelete = false;
		if (delete != null && delete != JsonNull.INSTANCE) {
			isDelete = delete.getAsBoolean();
		}

		return isDelete;
	}

	public String toDeleteCommand(String id) {
		JsonObject delete = new JsonObject();
		delete.add("delete", new JsonPrimitive(id));

		return delete.toString();
	}

	public String toAddCommand(String json) {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		sb.append("\"add\":");
		sb.append("{");
		sb.append("\"doc\":");
		sb.append(json);
		sb.append("}");
		sb.append("}");

		return sb.toString();
	}

}
